package com.weaver.seconddev.custom.controller;
import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.authority.annotation.WeaPermission;
import com.weaver.ebuilder.datasource.api.entity.ExecuteSqlEntity;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.service.DataSetService;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.mail.send.entity.EmailTaskObj;
import com.weaver.mail.send.entity.MailResult;
import com.weaver.mail.send.rest.MailSendWorkService;
import com.weaver.seconddev.custom.util.CallApiUtil;
import com.weaver.teams.security.context.UserContext;
import com.weaver.teams.security.user.User;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Api(tags = "流程")
@RestController
@RequestMapping(value = {"/api/secondev/workflow"})
@WeaPermission(publicPermission = true)
public class DevTLWorkflowController {
    
    @Autowired
    private RecordSet recordSet;
    
    @Autowired
    private RecordSet recordSet2;
    
    @Autowired
    private RecordSet rs;
    
    
    @Autowired
    private DataSetService dataSetService;
 
    @Autowired
    private ResourceComInfo resourceComInfo;
    @RpcReference
    private MailSendWorkService mailSendWorkService;
    
    
    /**
     * 流程提交时，先计算是否满足二开功能 （判断建模表是否有配置流程的需要指定提交的节点与字段信息）
     * @param headers
     * @param params
     * @return
     */
    @PostMapping({"/TriggerSubWf"})
    @ApiOperation("流程按钮")
    public JSONObject TriggerSubWf(@RequestHeader Map<String,String> headers,
                                    @RequestBody Map<String, Object>params) {
        log.error("=====TriggerSubWf===params:{}==",params);
        JSONObject responseObj = new JSONObject();
        try {
            String mainRequestId = Util.null2String(params.get("mainRequestId"));//mainRequestId
            Long userIdStr = Util.getLongValue(params.get("userIdStr"));//userIdStr
            Long workflowid = Util.getLongValue(params.get("workflowid"));//workflowid
            Long subWfSetIds = Util.getLongValue(params.get("subWfSetIds"));//subWfSetIds
            /** 通过后台管理中心-开放平台-开发者资料 中获取  */
            String host = Util.null2String(params.get("host"));//host
            String corpid = Util.null2String(params.get("corpid"));//corpid
            /** 通过后台管理中心-开放平台-应用管理--打开对应的应用 中获取  */
            String app_key = Util.null2String(params.get("app_key"));//app_key
            /** 通过后台管理中心-开放平台-开发者资料--打开对应的应用 中获取  */
            String app_secret = Util.null2String(params.get("app_secret"));//app_secret
            log.error("=====TriggerSubWf===mainRequestId:{}===userIdStr:{}===subWfSetIds:{}", mainRequestId, userIdStr, subWfSetIds);
            log.error("=====TriggerSubWf===host:{}==corpid:{}===app_key:{}==app_secret:{}", host, corpid, app_key, app_secret);
            
            //获取code
            String code = CallApiUtil.getCode(host, corpid);
            log.error("=====TriggerSubWf===code:{}==", code);
            
            //获取accessToken
            String accessToken = CallApiUtil.getAccessToken(host, code, app_key, app_secret);
            log.error("=====TriggerSubWf===accessToken:{}==", accessToken);
            String url = host + "/papi/openapi/api/workflow/core/paService/v1/triggerSubRequest";
            List subWfSetIdslist = new ArrayList();
            subWfSetIdslist.add(subWfSetIds);
            
            JSONObject param = new JSONObject();
            param.put("access_token", accessToken);
            param.put("userIdStr", userIdStr);
            param.put("mainRequestId", mainRequestId);
            param.put("subWfSetIds", subWfSetIdslist);
            // param.put("dataId",0);
            
            // 远程调用创建流程。
            HttpResponse response = HttpRequest.post(url)
                        .header("Content-Type", "application/json")  // 设置内容类型为JSON
                        .body(param.toString())  // 设置请求体
                        .execute();
            
            log.error("=====TriggerSubWf===response:{}==", response);
            // 获取响应状态码和响应体
            int statusCode = response.getStatus();
            String responseBody = response.body();
            log.error("=====TriggerSubWf===statusCode:{}==", statusCode);
            log.error("=====TriggerSubWf===responseBody:{}==", responseBody);
            responseObj = JSONObject.parseObject(responseBody);
        }catch (Exception e){
            log.error("=====TriggerSubWf===e:{}==", e);
        }
        log.error("=====TriggerSubWf===responseObj:{}==", responseObj);
        return responseObj;
    }
    
    
    
    
    
    
    /**
     * 流程提交时，先计算是否满足二开功能 （判断建模表是否有配置流程的需要指定提交的节点与字段信息）
     * @param headers
     * @param params
     * @return
     */
    @PostMapping({"/getTriggerSubWfMenu"})
    @ApiOperation("流程按钮")
    public JSONObject getTriggerSubWfMenu(@RequestHeader Map<String,String> headers,
                               @RequestBody Map<String, Object>params) {
        JSONObject jsonObject = new JSONObject();
        Long requestId = Util.getLongValue(params.get("requestId"));//requestId
        Long nodeid = Util.getLongValue(params.get("nodeId"));//fixedNodeId
        Long workflowid = Util.getLongValue(params.get("workflowId"));//workflowid
        
        boolean showbutton = false;
        //查询是否有主流程
        rs.executeQuery("select wc1.requestid,wc1.mainrequestid,wc2.workflowid,wc1.creator from wfc_requestbase_dt wc1 left join wfc_requestbase wc2 on wc1.mainrequestid=wc2.requestid  where wc1.requestid="+requestId);
        if (rs.next()) {
            String mainrequestid = Util.null2String(rs.getString("mainrequestid"));
            String mainWorkflowid = Util.null2String(rs.getString("workflowid"));
            String creator = Util.null2String(rs.getString("creator"));
            String sql ="select * from uf_SubTriggerSet where zlcljid='"+mainWorkflowid+"' and sfqy=1";
            ExecuteSqlEntity executeSqlEntity = new ExecuteSqlEntity();
            executeSqlEntity.setSql(Base64.encode(sql));
            //groupid,可以访问  E10地址/api/datasource/ds/group?sourceType=LOGIC 获取
            executeSqlEntity.setGroupId("weaver-ebuilder-form-service");
            executeSqlEntity.setSourceType(SourceType.LOGIC);
            Map<String, Object> datas = dataSetService.executeSql(executeSqlEntity);
            log.error("=====getTriggerSubWf===datas{}",datas);
            //返回值的records是一个map集合
            List<LinkedHashMap<String, Object>> relationConfigList = (List<LinkedHashMap<String, Object>>)datas.get("records");
            log.error("=====getTriggerSubWf===relationConfigList.size{}",relationConfigList.size());
            log.error("=====getTriggerSubWf===relationConfigList{}",relationConfigList);
            
            if(null!=relationConfigList) {
                String zlccfszid ="";
                String zlcxsjd ="";
                String cfanmc ="";
                for (int i = 0; i < relationConfigList.size(); i++) {
                    LinkedHashMap<String, Object> records = relationConfigList.get(i);
                    zlccfszid = Util.null2String(records.get("zlccfszid"));//主流程触发设置ID
                    zlcxsjd = Util.null2String(records.get("zlcxsjd"));//子流程显示节点ID
                    cfanmc = Util.null2String(records.get("cfanmc"));//按钮名称
                }
                log.error("=====getTriggerSubWf===zlccfszid:{}===zlcxsjd:{}===cfanmc:{}",zlccfszid,zlcxsjd,cfanmc);
                
                String trinodeid = "";
                //通过设置ID查出触发节点
                recordSet.executeQuery("select trinodeid from wfp_subset where workflowid='"+mainWorkflowid+"'  and   isdiffwf=0  and tritype=2 and isenable=1 and id='"+zlccfszid+"'");
                if(recordSet.next()){
                    trinodeid= Util.null2String(recordSet.getString("trinodeid"));
                }
                log.error("=====getTriggerSubWf===trinodeid:{}===rs.getExecuteResult:{}==",trinodeid,recordSet.getExecuteResult());
                
//                String creator = "";
//                String subsetdetailid = "";
//                recordSet.executeQuery("select creator,subsetdetailid,subrequestid from wfc_subrequest where mainrequestid="+mainrequestid+" and subrequestid="+requestId);
//                if(recordSet.next()){
//                    creator= Util.null2String(recordSet.getString("creator"));
//                    subsetdetailid= Util.null2String(recordSet.getString("subsetdetailid"));
//                }
                log.error("=====getTriggerSubWf===creator:{}====rs.getExecuteResult:{}==",creator,recordSet.getExecuteResult());
                if (("," + zlcxsjd + ",").contains("," + trinodeid + ",") || zlcxsjd.equals("")) {
                    jsonObject.put("triname",cfanmc);
                    jsonObject.put("mainrequestid",mainrequestid);
                    jsonObject.put("mainWorkflowid",mainWorkflowid);
                    jsonObject.put("triggerNodeId",trinodeid);
                    jsonObject.put("zlccfszid",zlccfszid);
                    jsonObject.put("userIdStr",creator);
                    showbutton = true;
                }
            }
        }
        log.error("=====getTriggerSubWf===rs:{}==",rs.getExecuteResult());
        
        jsonObject.put("status",showbutton);
        log.error("=====getTriggerSubWf===showbutton:{}==",showbutton);
        return jsonObject;
    }
    
    
    
    @PostMapping({"/gethandleforward"})
    @ApiOperation("流程按钮")
    public String gethandleforward(@RequestHeader Map<String,String> headers,
                                 @RequestBody Map<String, Object>params) {
        User currentUser = UserContext.getCurrentUser();
        long employeeid = currentUser.getEmployeeId();
        String domainurl = Util.null2String(params.get("domainurl")); //域名
        String originurl = Util.null2String(params.get("originurl"));//原地址
        Long requestId = Util.getLongValue(params.get("requestId"));//requestId
        Long userCurrentNodeId = Util.getLongValue(params.get("userCurrentNodeId"));//fixedNodeId
        String showlog = Util.null2String(params.get("showlog")); //showlog
        String url = domainurl + originurl;
        if (showlog.equals("y")) {
            log.error("==forward===requestid:" + requestId + "===url：" + url);
        }
        String ishandleforward="0";
        try {
            recordSet.executeQuery("  select 1 from wfc_operate_el where requestid=? and delete_type=0 and operatetype=2 and target_user_id=?  and target_node_id=? ",requestId , employeeid,userCurrentNodeId);
            if(recordSet.next()){
                ishandleforward="1";
            }
            if(showlog.equals("y")) {
                log.error(ishandleforward+"=====requestid:" + requestId + "===employeeid:" + employeeid + "=====userCurrentNodeId:" + userCurrentNodeId+"===SQLRuse:"+recordSet.getExecuteResult());
            }
        }catch (Exception e){
            log.error("====标准批注接口失败==post==getMessage="+e.getMessage());
            log.error("====标准批注接口失败==post==e={}",e.getMessage());
        }
        return ishandleforward;
    }
    
    
    /**
     * 流程提交时，先计算是否满足二开功能 （判断建模表是否有配置流程的需要指定提交的节点与字段信息）
     * @param headers
     * @param params
     * @return
     */
    @PostMapping({"/getsubmittonodeid"})
    @ApiOperation("流程按钮")
    public String getsubmittonodeid(@RequestHeader Map<String,String> headers,
                                   @RequestBody Map<String, Object>params) {
        User currentUser = UserContext.getCurrentUser();
        String tenantKey = currentUser.getTenantKey();//租户
        long employeeid = currentUser.getEmployeeId();
        Long requestId = Util.getLongValue(params.get("requestId"));//requestId
        Long nodeid = Util.getLongValue(params.get("userCurrentNodeId"));//fixedNodeId
        Long workflowid = Util.getLongValue(params.get("workflowid"));//workflowid
        String showlog = Util.null2String(params.get("showlog")); //showlog
        boolean isSelectNextFlow = false;
        String submitnodeidcus = "0";
        if(showlog.equals("y")) {
            log.error("===getsubmittonodeid==requestid:" + requestId + "===employeeid:" + employeeid + "=====nodeid:" + nodeid+"===workflowid:"+workflowid);
        }
        try {
            // 获取建模表中配置的信息（建模表：需要更改建模数据源 todo）
            recordSet2.executeSql("select nodeids,fieldname from uf_wfsubmit_cus where workflowid="+workflowid, CONN_TYPE.ebuilder.getType());
            if(showlog.equals("y")) {
                log.error("==a=getsubmittonodeid=（建模）=requestid:" + requestId + "===employeeid:" + employeeid + "=====nodeid:" + nodeid+"===SQLRuse:"+recordSet2.getExecuteResult());
            }
            if (recordSet2.next()) {
                List<String> nodeidsListcus = new ArrayList<>();
                String nodeids = Util.null2String(recordSet2.getString("nodeids"));
                String fieldnamecus = Util.null2String(recordSet2.getString("fieldname"));
                if (!nodeids.equals("")){
                    nodeidsListcus = Arrays.asList(nodeids.split(","));
                }
                
                if (!isSelectNextFlow && nodeidsListcus.size() == 0 || nodeidsListcus.contains(nodeid+"")){
                    // 查询到对应字段的fieldid
                    String tablename = "";
                    // 用户自定义表名查询
                    String sql2 = " select table_name from form_table where form_id in( select relatekey from wfp_relateform where workflowid=?)";
                    recordSet.executeQuery(sql2,workflowid);
                    if (recordSet.next()){
                        tablename = Util.null2String(recordSet.getString("table_name"));
                    }
                    if(showlog.equals("y")) {
                        log.error("==getsubmittonodeid=（获取表名）=requestid:" + requestId + "===tablename:"+tablename+"==SQLRuse:"+recordSet.getExecuteResult());
                    }
                    
                 
                    String sql3 = "select f.* from "+tablename+"  f" +
                                          "   inner join wfc_form_data f2 on f.id=f2.dataid  where f2.requestid=?";
                    recordSet.executeQuery(sql3,requestId);
                    String form_value = "";
                    if(recordSet.next()){
                        form_value = Util.null2String( recordSet.getString(fieldnamecus) );
                    }
                    log.error("==getsubmittonodeid（获取字段值）=requestid:"+requestId+"==form_value:"+form_value+"===sql3:"+sql3+"===SQLRuse:"+recordSet.getExecuteResult());
                    
                    
                    String submitsqlcus = "select id from wfp_node where id =? and workflowid=? and tenant_key=?";
                    recordSet.executeQuery(submitsqlcus,form_value,workflowid,tenantKey);
                    if (recordSet.next() && !form_value.equals("") ){
                        submitnodeidcus=form_value;
                    }
                    log.error("==getsubmittonodeid（判断获取的节点是否是主干节点）=requestid:"+requestId+"=====submitsqlcus:"+submitsqlcus+"===SQLRuse:"+recordSet.getExecuteResult());
                }
            }
            if(showlog.equals("y")) {
                log.error("=b==getsubmittonodeid==requestid:" + requestId + "===employeeid:" + employeeid + "=====nodeid:" + nodeid+"===submitnodeidcus:"+submitnodeidcus);
            }
        }catch (Exception e){
            log.error("====获取submittonode失败==getMessage="+e.getMessage());
        }
        
        return submitnodeidcus;
    }
 
    
    
    
    @PostMapping({"/sendEmailforward"})
    @ApiOperation("流程提交时做相关功能处理")
    public JSONObject sendMail(@RequestHeader Map<String,String> headers,
                             @RequestBody Map<String, Object>params) {
        JSONObject returndata = new JSONObject();
        User currentUser = UserContext.getCurrentUser();
        String tenantKey = currentUser.getTenantKey();//租户
        long employeeid = currentUser.getEmployeeId();
        
        Long requestId = Util.getLongValue(params.get("requestId"));//requestId
        Long userCurrentNodeId = Util.getLongValue(params.get("userCurrentNodeId"));//fixedNodeId
        Long workflowid = Util.getLongValue(params.get("workflowid"));//requestId
        String showlog = Util.null2String(params.get("showlog")); //showlog
        
        String subject = Util.null2String(params.get("subject")); //subject
        String content = Util.null2String(params.get("content"));//原地址
        String email_url = Util.null2String(params.get("email_url"));//email_url
        String src = Util.null2String(params.get("src"));//src
        
        if(showlog.equals("y")) {
            log.error("==submit===requestid:" + requestId + "===employeeid:" + employeeid + "===subject:"+subject+"==contenthtml:" + content);
        }
        try {
            String requestname = "";
            recordSet.executeQuery(" select requestname from wfc_requestbase where requestid=? and tenant_key=?",requestId , tenantKey);
            if(recordSet.next()){
                requestname = Util.null2String(recordSet.getString("requestname"));
            }
            
            String ishandleforward = "";
            String zb_uid ="";
            String operatedatetime ="";
            recordSet.executeQuery(" select b.operatedatetime,a.userid from wfc_operate_el a left join wfc_requestlog b on a.request_log_id=b.id where a.requestid=? and a.delete_type=0 and a.operatetype=2 and a.target_user_id=?  and a.target_node_id=? order by a.id desc",requestId , employeeid,userCurrentNodeId);
            if(recordSet.next()){
                ishandleforward="1";
                zb_uid = Util.null2String(recordSet.getString("userid"));
                operatedatetime = Util.null2String(recordSet.getString("operatedatetime"));
            }
            if(showlog.equals("y")) {
                log.error(ishandleforward+"==响应（效验身份转办）===requestid:" + requestId + "===employeeid:" + employeeid + "===operatedatetime:"+operatedatetime+"==userCurrentNodeId:" + userCurrentNodeId+"===SQLRuse:"+recordSet.getExecuteResult());
            }
            if(!operatedatetime.equals("")){
                String receivedatetime = "";
                String sql ="select receivedatetime,nodeid from wfc_operate_done where requestid=? and delete_type=0 and user_master_id=? and nodeid=? and tenant_key=? and isremark in(100,101) and preisremark in(0,1) order by id desc";
                recordSet.executeQuery(sql,requestId,employeeid,userCurrentNodeId,tenantKey);
                if(recordSet.next()){
                    receivedatetime = Util.null2String(recordSet.getString("receivedatetime"));
                }
                if(showlog.equals("y")) {
                    log.error(ishandleforward+"==响应=（当前用户的待办表接收日期）==requestid:" + requestId + "===employeeid:" + employeeid + "===operatedatetime:"+operatedatetime+"==receivedatetime:" + receivedatetime+"===SQLRuse:"+recordSet.getExecuteResult());
                }
                //接收日期与操作日期相同
                if(receivedatetime.equals(operatedatetime)){
                    //代表是转办操作者
                    ishandleforward="1";
                }else{
                    ishandleforward="0";
                }
            }
            if(showlog.equals("y")) {
                log.error(ishandleforward+"==响应=（当前用户的待办表接收日期）==requestid:" + requestId + "===ishandleforward:" + ishandleforward );
            }
            //转办身份
            if(ishandleforward.equals("1")){
                sendEmailforward( ishandleforward , requestname,  src , zb_uid , requestId,  workflowid,  subject , content, email_url , showlog);
            }
            returndata.put("status",true);
        }catch (Exception e){
            log.error("====标准提交接口失败==post==getMessage="+e.getMessage());
            log.error("====标准批注接口失败==post==e={}",e.getMessage());
            returndata.put("status",false);
        }
        return returndata;
    }
    
    
    
    
    @PostMapping({"/submit"})
    @ApiOperation("流程提交时做相关功能处理")
    public JSONObject submit(@RequestHeader Map<String,String> headers,
                             @RequestBody Map<String, Object>params) {
        JSONObject returndata = new JSONObject();
        User currentUser = UserContext.getCurrentUser();
        String tenantKey = currentUser.getTenantKey();//租户
        long employeeid = currentUser.getEmployeeId();
        
        Long requestId = Util.getLongValue(params.get("requestId"));//requestId
        Long userCurrentNodeId = Util.getLongValue(params.get("userCurrentNodeId"));//fixedNodeId
        Long workflowid = Util.getLongValue(params.get("workflowid"));//requestId
        String showlog = Util.null2String(params.get("showlog")); //showlog
        
        String subject = Util.null2String(params.get("subject")); //subject
        String content = Util.null2String(params.get("content"));//原地址
        String email_url = Util.null2String(params.get("email_url"));//email_url
        String src = Util.null2String(params.get("src"));//src
        String domainurl = Util.null2String(params.get("domainurl")); //域名
        String originurl = Util.null2String(params.get("originurl"));//原地址
        
        String url = domainurl + originurl;
        if (showlog.equals("y")) {
            log.error("==submit===requestid:" + requestId + "===url：" + url);
        }
        if(showlog.equals("y")) {
            log.error("==submit===requestid:" + requestId + "===employeeid:" + employeeid + "===subject:"+subject+"==contenthtml:" + content);
        }
        try {
            String requestname = "";
            recordSet.executeQuery(" select requestname from wfc_requestbase where requestid=? and tenant_key=?",requestId , tenantKey);
            if(recordSet.next()){
                requestname = Util.null2String(recordSet.getString("requestname"));
            }
            
            String ishandleforward = "";
            String zb_uid ="";
            String operatedatetime ="";
            recordSet.executeQuery(" select b.operatedatetime,a.userid from wfc_operate_el a left join wfc_requestlog b on a.request_log_id=b.id where a.requestid=? and a.delete_type=0 and a.operatetype=2 and a.target_user_id=?  and a.target_node_id=? ",requestId , employeeid,userCurrentNodeId);
            if(recordSet.next()){
                ishandleforward="1";
                zb_uid = Util.null2String(recordSet.getString("userid"));
                operatedatetime = Util.null2String(recordSet.getString("operatedatetime"));
            }
            if(showlog.equals("y")) {
                log.error(ishandleforward+"==（效验身份转办）===requestid:" + requestId + "===employeeid:" + employeeid + "===operatedatetime:"+operatedatetime+"==userCurrentNodeId:" + userCurrentNodeId+"===SQLRuse:"+recordSet.getExecuteResult());
            }
            if(!operatedatetime.equals("")){
                String receivedatetime = "";
                String sql ="select receivedatetime,nodeid from wfc_operate_todo where requestid=? and delete_type=0 and user_master_id=? and nodeid=? and tenant_key=? and isremark in(0,1)";
                recordSet.executeQuery(sql,requestId,employeeid,userCurrentNodeId,tenantKey);
                if(recordSet.next()){
                    receivedatetime = Util.null2String(recordSet.getString("receivedatetime"));
                }
                if(showlog.equals("y")) {
                    log.error(ishandleforward+"===（当前用户的待办表接收日期）==requestid:" + requestId + "===employeeid:" + employeeid + "===operatedatetime:"+operatedatetime+"==receivedatetime:" + receivedatetime+"===SQLRuse:"+recordSet.getExecuteResult());
                }
                //接收日期与操作日期相同
                if(receivedatetime.equals(operatedatetime)){
                    //代表是转办操作者
                    ishandleforward="1";
                }else{
                    ishandleforward="0";
                }
            }
      
            String bodyStr = JSON.toJSONString(params);
            if (showlog.equals("y")) {
                log.error("==submit===requestid:" + requestId +"===url:"+url+ "=标准接口的参数==bodyStr：" + bodyStr);
            }
            String postresultStr = HttpRequest.post(url).headerMap(headers, true).disableCookie().body(bodyStr).timeout(6000).execute().body();
            if (showlog.equals("y")) {
                log.error("==submit===requestid:" + requestId + "===postresultStr：" + postresultStr);
            }
            returndata =JSONObject.parseObject(postresultStr);
            
            //转办身份
            if(ishandleforward.equals("1")){
                sendEmailforward( ishandleforward , requestname,  src , zb_uid , requestId,  workflowid,  subject , content, email_url , showlog);
            }
            
            
        }catch (Exception e){
            log.error("====标准提交接口失败==post==getMessage="+e.getMessage());
            log.error("====标准批注接口失败==post==e={}",e.getMessage());
        }
        return returndata;
    }
    
    
    /**
     * 发送邮件
     * @param ishandleforward
     * @param requestname
     * @param src
     * @param zb_uid
     * @param requestId
     * @param workflowid
     * @param subject
     * @param content
     * @param email_url
     * @param showlog
     * @return
     */
    public void sendEmailforward(String ishandleforward ,String requestname, String src ,String zb_uid ,Long requestId, Long workflowid, String subject ,String content,String email_url ,String showlog) {
        User currentUser = UserContext.getCurrentUser();
        String tenantKey = currentUser.getTenantKey();//租户
        if(ishandleforward.equals("1")){
            String tablename = "";
            // 用户自定义表名查询
            String sql2 = " select table_name from form_table where form_id in( select relatekey from wfp_relateform where workflowid=?)";
            recordSet.executeQuery(sql2,workflowid);
            if (recordSet.next()){
                tablename = Util.null2String(recordSet.getString("table_name"));
            }
            if(showlog.equals("y")) {
                log.error(ishandleforward+"==响应=（当前用户的待办表接收日期）==requestid:" + requestId + "====SQLRuse:"+recordSet.getExecuteResult());
            }
        
            try {
                //转办人的邮箱
                String email = resourceComInfo.getEmail(""+zb_uid);
                String username = resourceComInfo.getLastname(zb_uid);
                
                if(showlog.equals("y")) {
                    log.error(ishandleforward+"==响应=（当前用户的待办表接收日期）==requestid:" + requestId + "====email:"+email +"===username:"+username);
                }
                
                subject= getContent( requestId,  email_url , requestname ,  src, username , subject,tablename);
                content= getContent( requestId,  email_url , requestname ,  src, username , content,tablename);
                if (showlog.equals("y")) {
                    log.error("=====requestid:" + requestId + "====subject:" + subject +"===content:"+content);
                }
                
                //邮件主体
                EmailTaskObj emailTaskObj = new EmailTaskObj();
                emailTaskObj.setSubject(subject);//主题
                emailTaskObj.setContentHtml(content);//内容
                emailTaskObj.setToList(email);//收件人邮箱集合
                emailTaskObj.setTenantKey(tenantKey);//租户
                //发送邮件
                if (showlog.equals("y")) {
                    log.error("=====requestid:" + requestId + "===开始发邮件啦==" + "=====email:" + email);
                }
                MailResult mailResult = mailSendWorkService.sendRemindMail(emailTaskObj);
                if (showlog.equals("y")) {
                    log.error("======requestid:" + requestId + "===zb_uid:" + zb_uid + "===subject:" + subject + "===Msg:" + mailResult.getMsg() + "===Success:" + mailResult.getSuccess());
                }
            }catch (Exception e){
                if (showlog.equals("y")) {
                    log.error("=====(异常)=requestid:" + requestId + "====e:" + e);
                }
            }
        }
    }
    
    
    
    
    
    /**
     * 获取到邮件内容
     * @param src
     * @return
     */
    public String getContent(Long requestid,String email_url ,String requestname , String src,String username ,String content , String tablename){
        // 流程标题查询
        requestname = "<a href='"+email_url+requestid+"'>"+requestname+"</a>";
        // 定义正则，解析邮件内容,解析字段名
        Pattern pattern = Pattern.compile("\\{([a-zA-Z0-9_]+)\\}");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()){
            String group = matcher.group();
            if (group.equals("{pt_src}")) {
                src = src.equals("submit")?"批准":"拒绝";
                content = content.replace(group,src);
                continue;
            }
            if (group.equals("{pt_requestname}")) {
                content = content.replace(group,requestname);
                continue;
            }
            if (group.equals("{pt_transfer}")){
                content = content.replace(group,username);
                continue;
            }
            // 字段处理  // 查询字段，并替换内容
            String field = group.replace("{", "").replace("}", "");
            String sql3 = "select f.* from "+tablename+"  f" +
                           "   inner join wfc_form_data f2 on f.id=f2.dataid  where f2.requestid=?";
            log.error("===requestid:"+requestid+"=====field:"+field+"=sql3:"+sql3);
            recordSet.executeQuery(sql3,requestid);
            if (recordSet.next()){
                content = content.replace(group,Util.null2String(recordSet.getString(field),""));
            } else {
                content = content.replace(group,field);
            }
        }
        log.error("===requestid:"+requestid+"===content:"+content);
        return content;
    }
    
    
}
